import { defineStore } from 'pinia'
import { asyncRouterMap, constantRouterMap } from '@/router'
import { generateRoutesWeb, generateRoutesAfter, flatMultiLevelRoutes, filterKeepAlive } from '@/utils/routerHelper'
import { cloneDeep } from 'lodash-es'
import { store } from '../index'
import { useAppStoreWithOut } from '@/stores/modules/app'
const appStore = useAppStoreWithOut()
export interface PermissionState {
  routers: AppRouteRecordRaw[]
  addRouters: AppRouteRecordRaw[]
  cacheRoutes: string[]
}

export const usePermissionStore = defineStore('permission', {
  state: (): PermissionState => ({
    routers: [],
    addRouters: [],
    cacheRoutes: [],
  }),
  getters: {
    getRouters(): AppRouteRecordRaw[] {
      return this.routers
    },
    getAddRouters(): AppRouteRecordRaw[] {
      return flatMultiLevelRoutes(cloneDeep(this.addRouters))
    },
    keepAliveRoutes(): string[] {
      this.cacheRoutes = filterKeepAlive(this.routers)
      return this.cacheRoutes
    },
  },
  actions: {
    setRouters(routers: AppCustomRouteRecordRaw[]): void {
      this.routers = routers
    },
    generateRoutes(
      type: string,
      routers?: AppCustomRouteRecordRaw[] | string[]
    ): Promise<unknown> {
      return new Promise<void>((resolve) => {
        let routerMap: AppRouteRecordRaw[] = []
        if (type === 'back-end') {
          // 模拟后端过滤菜单
          routerMap = generateRoutesAfter(routers as AppCustomRouteRecordRaw[])
        } else if (type === 'front-end') {
          // 模拟前端过滤菜单
          const userRolses = appStore.getUserInfo?.roles
          routerMap = generateRoutesWeb(cloneDeep(asyncRouterMap), userRolses)
        } else {
          // 直接读取静态路由表
          routerMap = cloneDeep(asyncRouterMap)
        }
        // 动态路由，404一定要放到最后面
        this.addRouters = routerMap.concat([
          {
            path: '/:path(.*)*',
            redirect: '/404',
            name: '404Page',
            meta: {
              hidden: true,
              breadcrumb: false
            }
          }
        ])
        // 渲染菜单的所有路由
        this.routers = cloneDeep(constantRouterMap).concat(routerMap)
        resolve()
      })
    },
  }
})

export const usePermissionStoreWithOut = () => {
  return usePermissionStore(store)
}
